﻿using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YMSoft.SqLite
{
    public abstract class RepositoryBase<T> where T : class
    {
        public RepositoryBase()
        {
            this.DB = new YMSOFTDB("conn");
        }


        public RepositoryBase(DataConnection db)
        {
            this.DB = db;
        }

        public DataConnection DB { get; private set; }


        protected IQueryable<T> GetTable()
        {
            return DB.GetTable<T>();
        }

        public void Save(T entity)
        {
            var keyValue = KeyValue(entity);
            if (keyValue == 0)
            {
                DB.Insert(entity);
            }
            else
            {
                DB.Update(entity);
            }
        }

        string keyName = null;
        public string KeyName
        {
            get
            {
                if (keyName == null)
                {
                    var pi = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).Length > 0).FirstOrDefault();
                    if (pi == null)
                    {
                        throw new Exception("没有找到主键.");
                    }
                    keyName = pi.Name;
                }
                return keyName;
            }
        }

        public long KeyValue(T entity)
        {
            var p = typeof(T).GetProperty(KeyName);
            var result = p.GetValue(entity, null);
            return (long)result;
        }
    }
}
